﻿using Greg.XmlEditor.Presentation.Presenters;
namespace Greg.XmlEditor.Presentation.Commands.Concrete
{
	public class OpenSchemaCommand : CommandBase
	{
		private readonly MasterPresenter presenter;
		private readonly IInteractionManager interaction;

		public OpenSchemaCommand(MasterPresenter presenter, IInteractionManager interaction)
		{
			this.presenter = presenter;
			this.interaction = interaction;
		}

		/// <summary>
		/// Refreshes the command state.
		/// </summary>
		public override void Refresh()
		{
			this.IsEnabled = (this.presenter.CurrentDocument != null);
		}

		/// <summary>
		/// Executes the command logics.
		/// </summary>
		public override void Invoke()
		{
			var schema = this.GetSchema();
			if (schema == null) return;

			var filename = schema.FullPath;
			if (!this.interaction.AskForSchemaFile(ref filename)) return;

			schema.Open(filename);
			this.presenter.CurrentDocument = schema;
		}

		private SchemaPresenter GetSchema()
		{
			var document = this.presenter.CurrentDocument;
			if (document is DocumentPresenter)
			{
				return ((DocumentPresenter)document).Schema;
			}
			if (document is SchemaPresenter)
			{
				return (SchemaPresenter)document;
			}
			if (document is StylePresenter)
			{
				return ((StylePresenter)document).Document.Schema;
			}
			return null;
		}
	}
}
